'''
    @Author:webrainer
    @Date:today
    @Version:
    @Since:python3.11
    @See:
    @Description:配置读取模块，实现了在任意路径下读取配置文件的基本功能
    @Functions:

    使用示例
    # 导入模块
    from utils.config_reader import ConfigReader
    config_reader = ConfigReader()

    # 获取值
    database_host = config_reader.get_value('database_dev', 'host')
    database_port = config_reader.get_int_value('database_dev', 'port')

    # 打印值
    print(database_host)
    print(database_port)
'''

import configparser
import os


class ConfigReader:

    #获取当前文件路径
    cur_path = os.path.dirname(os.path.realpath(__file__))
    print(cur_path)

    def __init__(self):
        #获取当前路径
        cur_path = os.path.dirname(os.path.realpath(__file__))
        self.config = configparser.ConfigParser()
        #拼接路径
        config_path = os.path.join(cur_path, "../config.ini")
        self.config.read(config_path)

    def get_value(self, section, option):
        try:
            value = self.config.get(section, option)
            return value
        except (configparser.NoSectionError, configparser.NoOptionError):
            return None

    def get_int_value(self, section, option):
        value = self.get_value(section, option)
        if value is not None:
            try:
                return int(value)
            except ValueError:
                return None
        return None

    def get_float_value(self, section, option):
        value = self.get_value(section, option)
        if value is not None:
            try:
                return float(value)
            except ValueError:
                return None
        return None

    def get_boolean_value(self, section, option):
        value = self.get_value(section, option)
        if value is not None:
            return value.lower() in ['true', 'yes', '1']
        return None


#test
if __name__=="__main__":
    config_reader = ConfigReader()
    database_host = config_reader.get_value('database_dev', 'host')
    database_port = config_reader.get_int_value('database_dev', 'port')
    print(database_host)
    print(database_port)